package com.yumaolin.deepunderstand.leetcode.algorithm.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 145.后序遍历的非递归实现
 */
public class PostOrderTraversal {

    public static void main(String[] args) {
        PostOrderTraversal postOrderTraversal = new PostOrderTraversal();
        PostOrderTraversal.TreeNode treeNode2 = new PostOrderTraversal().new TreeNode(2);
        PostOrderTraversal.TreeNode treeNode3 = new PostOrderTraversal().new TreeNode(3);
        PostOrderTraversal.TreeNode treeNode = new PostOrderTraversal().new TreeNode(1, treeNode2, treeNode3);
        System.out.println(postOrderTraversal.preorderTraversal(treeNode));
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> sortList = new ArrayList<>();
        if (root == null) {
            return sortList;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (!stack.empty() || cur != null) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev) {
                stack.pop();
                prev = top;
                sortList.add(top.val);
            } else {
                cur = top.right;
            }
        }
        return sortList;
    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
